<?php
// 【最终完整版】m-merchant/agent_data.php

header('Content-Type: application/json; charset=utf-8');

// --- 完整的Token验证逻辑 ---
function verify_token($token) {
    $secret_key = 'kkcc.vip-is-the-best-!@#$%'; // !!重要!! 必须和 login_handler.php 中的密钥完全一致
    if (!$token) return null;
    $token_parts = explode('.', $token);
    if (count($token_parts) !== 3) return null;
    list($base64UrlHeader, $base64UrlPayload, $base64UrlSignature) = $token_parts;
    $signature = base64_decode(str_replace(['-', '_'], ['+', '/'], $base64UrlSignature));
    $expectedSignature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secret_key, true);
    if (!hash_equals($expectedSignature, $signature)) return null;
    $payload_decoded = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $base64UrlPayload)), true);
    if ($payload_decoded === null || ($payload_decoded['exp'] ?? 0) < time()) return null;
    return $payload_decoded['data'];
}
function get_authorization_header() {
    $headers = null;
    if (isset($_SERVER['Authorization'])) { $headers = trim($_SERVER["Authorization"]); }
    else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { $headers = trim($_SERVER["HTTP_AUTHORIZATION"]); }
    elseif (function_exists('getallheaders')) {
        $requestHeaders = getallheaders();
        $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
        if (isset($requestHeaders['Authorization'])) { $headers = trim($requestHeaders['Authorization']); }
    }
    return $headers;
}
$auth_header = get_authorization_header();
$token = $auth_header ? str_replace('Bearer ', '', $auth_header) : '';
$user_data = verify_token($token);
if ($user_data === null) {
    http_response_code(401);
    echo json_encode(['status' => -99, 'msg' => '登录失效或Token无效，请重新登录。']);
    exit();
}

include_once("../untils/conn.php");
mysqli_query($con, "set names utf8");

$current_proxy_id = (int)$user_data['proxy_id'];
$current_proxy_acc = mysqli_real_escape_string($con, $user_data['proxy_acc']);
$keyword = $_POST['keyword'] ?? '';

// 1. 查询下级代理列表及其贡献佣金
$sql_list = "
    SELECT 
        p.proxy_id, p.proxy_name, p.proxy_acc, p.proxy_phone, p.cr_time, p.proxy_sta, p.proxy_rename,
        COALESCE(SUM(r.price), 0) as total_commission_contribution
    FROM proxy p
    LEFT JOIN oder o ON p.proxy_id = o.proxy_id
    LEFT JOIN revenue r ON o.oderid = r.oderid AND r.proxy_upid = '{$current_proxy_acc}'
    WHERE p.proxy_upid = '{$current_proxy_id}'
";
if (!empty($keyword)) {
    $keyword_safe = mysqli_real_escape_string($con, $keyword);
    $sql_list .= " AND (p.proxy_name LIKE '%{$keyword_safe}%' OR p.proxy_acc LIKE '%{$keyword_safe}%' OR p.proxy_phone LIKE '%{$keyword_safe}%')";
}
$sql_list .= " GROUP BY p.proxy_id ORDER BY p.proxy_id DESC";

$result_list = mysqli_query($con, $sql_list);
$agents_list = [];
if ($result_list) {
    while($row = mysqli_fetch_assoc($result_list)) {
        $agents_list[] = [
            'id'        => $row['proxy_id'],
            'name'      => $row['proxy_name'] ?: '未命名',
            'real_name' => $row['proxy_rename'] ?? '未实名',
            'account'   => $row['proxy_acc'],
            'phone'     => $row['proxy_phone'],
            'status'    => $row['proxy_sta'],
            'join_time' => date('Y-m-d H:i', $row['cr_time']),
            'commission_contribution' => number_format((float)$row['total_commission_contribution'], 2)
        ];
    }
}

// 2. 查询统计数据
$sql_stats = "SELECT COUNT(*) as total_agents, SUM(CASE WHEN proxy_sta = 1 THEN 1 ELSE 0 END) as active_agents FROM proxy WHERE proxy_upid = '{$current_proxy_id}'";
$res_stats = mysqli_query($con, $sql_stats);
$stats_data = $res_stats ? mysqli_fetch_assoc($res_stats) : ['total_agents' => 0, 'active_agents' => 0];

// 3. 准备招募链接 (请确保您根目录有register.php或修改此链接)
$recruitment_link = "http://{$_SERVER['HTTP_HOST']}/register.php?puid={$current_proxy_id}";

// 4. 最终返回数据
echo json_encode([
    'status' => 0,
    'data' => [
        'list' => $agents_list,
        'stats' => [
            'total_agents' => (int)($stats_data['total_agents'] ?? 0),
            'active_agents' => (int)($stats_data['active_agents'] ?? 0),
            'recruitment_link' => $recruitment_link
        ]
    ]
]);
mysqli_close($con);
?>